<script setup lang="ts">
import { ref, computed, watch, defineProps, defineEmits } from 'vue';

const props = defineProps({
  standardValue: {
    type: String,
    default: ''
  }
});

const emit = defineEmits(['update:standardValue']);

// 定义默认值
// const defaultStandard = [
//   { key: 1, label: "长", value: "0" },
//   { key: 2, label: "宽", value: "0" },
//   { key: 3, label: "高", value: "0" }
// ];
const defaultStandard = [
  { key: 1, label: '', value: '' }
];

// 使用 ref 创建一个响应式的内部状态
const internalState = ref([...defaultStandard]);

// 计算属性用于获取当前值
const timeStandardValue = computed(() => internalState.value);

// 监听 standardValue 变化，初始化或解析 JSON 字符串到 internalState
watch(() => props.standardValue, (newVal) => {
  if (!newVal || newVal === '') {
    internalState.value = [...defaultStandard];
  } else {
    try {
      const parsedValue = JSON.parse(newVal);
      if (Array.isArray(parsedValue)) {
        internalState.value = parsedValue;
      } else {
        console.error('Invalid JSON structure:', newVal);
        internalState.value = [...defaultStandard];
      }
    } catch (e) {
      console.error('Invalid JSON string:', e);
      internalState.value = [...defaultStandard];
    }
  }
}, { immediate: true });

// 监听内部状态变化，更新父组件的 standardValue 属性
watch(internalState, (newVal) => {
  emit('update:standardValue', JSON.stringify(newVal));
}, { deep: true });

// 规格移除按钮逻辑
const removeOneStandard = (key:any) => {
  internalState.value = internalState.value.filter(item => item.key !== key);
};

// 规格新增按钮逻辑
const addOneStandard = () => {
  const newKey = internalState.value.length > 0 ? Math.max(...internalState.value.map(item => item.key)) + 1 : 1;
  const newItem = { key: newKey, label: '', value: '' };
  internalState.value.push(newItem);
};
</script>

<template>
  <el-space direction="vertical">
    <el-row :gutter="1" v-for="(item) in timeStandardValue" :key="item.key">
      <el-col :xs="24" :lg="5">
        <el-input v-model="item.label" placeholder="名称"></el-input>
      </el-col>
      <el-col :xs="24" :lg="15">
        <el-input v-model="item.value" placeholder="内容">
          <template v-if="['长', '宽', '高'].includes(item.label)" #append>毫米</template>
        </el-input>
      </el-col>
      <el-col :xs="24" :lg="2">
        <el-button @click="removeOneStandard(item.key)" icon="el-icon-delete" circle></el-button>
      </el-col>
    </el-row>
  </el-space>
  <span>
    <el-button @click="addOneStandard" icon="el-icon-circle-plus-outline" circle></el-button>
  </span>
</template>

<style scoped lang="scss">

</style>
